import {
  WSController,
  OnWSConnection,
  OnWSMessage,
  Provide,
  Inject,
} from '@midwayjs/decorator';
import { Context } from '@midwayjs/socketio';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { MessageEntity } from '@/entity/message';
import { GroupMsgEntity } from '@/entity/groupMsg';
import { MsgSessionEntity } from '@/entity/msgSession';
import { GroupUserEntity } from '@/entity/groupUser';
// import { OfflineMsgEntity } from '@entity/offlineMsg';

const users = [];
const groupList = [];

@Provide()
@WSController('/')
export class IndexSocketController {
  @InjectEntityModel(MessageEntity)
  messageEntity: Repository<MessageEntity>;

  @InjectEntityModel(GroupMsgEntity)
  groupMsgEntity: Repository<GroupMsgEntity>;

  @InjectEntityModel(GroupUserEntity)
  groupUserEntity: Repository<GroupUserEntity>;

  @InjectEntityModel(MsgSessionEntity)
  msgSessionEntity: Repository<MsgSessionEntity>;

  // @InjectEntityModel(OfflineMsgEntity)
  // offlineMsgEntity: Repository<OfflineMsgEntity>;

  // @Inject()
  // tokenUtil: TokenUtil;

  @Inject()
  ctx: Context | any;

  @OnWSConnection()
  async onConnectionMethod() {
    // console.log('on client connect', this.ctx.id);
    // console.log('on client connect', this.ctx.handshake.auth);
    // const username = this.ctx.handshake.auth.username;
  }

  @OnWSMessage('login')
  async login(user) {
    // console.log('user', user);
    this.ctx.username = user.username;
    this.ctx.userID = user.id;
    const userFind = users.find((item: any) => item.userId === user.id);
    if (userFind) {
      users.forEach((item: any) => {
        if (item.userId === user.id) {
          item.socketId = this.ctx.id;
        }
      });
    } else {
      users.push({
        socketId: this.ctx.id,
        userId: user.id,
        username: user.username,
      });
    }
    console.log('loginResult', users);
  }
  @OnWSMessage('private_message')
  async private_message(params) {
    const { name, content, imgUrl, time, toId, fromId, contentType } = params;
    console.log('params', params);
    console.log('form', fromId);
    /* 遍历数组 */
    console.log('users', users);
    console.log('contentType', contentType);

    const emitParams = {
      fromId: fromId,
      toId: toId,
      name: name,
      imgUrl: imgUrl,
      content: content,
      contentType: contentType,
      chatType: 1,
      unreadCount: 1,
      type: 2,
      time: time,
    };
    users.forEach(async s => {
      /* 判断该对象是不是我们需要发送的那个人 */
      if (Number(s.userId) === Number(toId)) {
        /* 发送数据 */
        this.ctx.to(s.socketId).emit('chat_one', {
          ...emitParams,
        });
      }
    });
    // const userResult = await users.find(
    //   (item: any) => Number(item.userId) === Number(item.toId)
    // );
    // if (!userResult) {
    //   this.offlineMsgEntity.save(emitParams);
    // }
    const _params = {
      fromId,
      toId: toId,
      content,
      contentType: contentType,
      status: 1,
      time,
    };

    await this.messageEntity.save(_params);
    const msgSessionData = await this.msgSessionEntity.findOne({
      where: { fromId, toId },
    });
    if (msgSessionData) {
      console.log('dddd', params);
      this.msgSessionEntity
        .createQueryBuilder('msg')
        .update()
        .set({
          name: name, // 最后一条消息发送者名字
          imgUrl: imgUrl, // 最后一条消息发送者头像
          content: content, // 聊天内容
          contentType: contentType, // 聊天消息类型 1 文字 2 图片 3 文件 4 其他
          unreadCount: msgSessionData.unreadCount + 1, // 消息未读数
          time: time, // 发送时间
        })
        .where({ fromId, toId })
        .execute();
    } else {
      const msgParams = {
        fromId: fromId, // 发送者id
        toId: toId, // 接受者id
        name: name, // 最后一条消息发送者名字
        imgUrl: imgUrl, // 最后一条消息发送者头像
        content: content, // 聊天内容
        contentType: contentType, // 聊天消息类型 1 文字 2 图片 3 文件 4 其他
        chatType: 1, // 聊天类型 1 单聊 2 群聊
        unreadCount: 1, // 消息未读数
        time: time, // 发送时间
      };
      this.msgSessionEntity.save(msgParams);
    }
  }
  // 加入群
  @OnWSMessage('group_join')
  async groupJoin(options) {
    console.log('加入群', options);
    groupList.push({
      socketId: this.ctx.id,
      groupId: options.groupId,
      userId: options.userId,
    });
  }
  // 群消息
  @OnWSMessage('group_message')
  async groupMessage(options) {
    const {
      name,
      content,
      imgUrl,
      time,
      fromId,
      toId,
      contentType,
      groupName,
      groupImgUrl,
    } = options;
    // console.log('群消息', toId);
    // console.log('groupList', groupList);
    const groupUser = await this.groupUserEntity.find({
      where: {
        groupId: toId,
      },
    });
    // 群成员对应的socketId
    /* 遍历数组 */
    groupUser.forEach((item: any) => {
      /* 判断该对象是不是我们需要发送的那个人 */
      if (item.groupId === toId) {
        const userRes = users.find((a: any) => a.userId === item.userId);
        if (userRes && userRes.socketId) {
          this.ctx.to(userRes.socketId).emit('group_chat_session', {
            fromId: toId,
            toId: fromId,
            name: groupName,
            imgUrl: groupImgUrl,
            content: content,
            contentType: contentType,
            chatType: 2,
            type: 2,
            unreadCount: 1,
            time: time,
          });
          this.ctx.to(userRes.socketId).emit('group_chat_one', {
            fromId: toId,
            toId: fromId,
            name: name,
            imgUrl: imgUrl,
            content: content,
            contentType: contentType,
            chatType: 2,
            type: 2,
            unreadCount: 1,
            time: time,
          });
        }
      }
    });
    const _params = {
      userId: fromId,
      groupId: toId,
      content: content,
      contentType: contentType,
      status: 1,
      time,
    };
    await this.groupMsgEntity.save(_params);

    // const msgSessionData = await this.msgSessionEntity.findOne({
    //   where: { chatType: 2, toId },
    // });
    // console.log('msgSessionData', msgSessionData);
    // if (msgSessionData) {
    //   console.log('dddd', options);
    //   console.log('msgSessionData', msgSessionData);
    //   this.msgSessionEntity
    //     .createQueryBuilder('msg')
    //     .update()
    //     .set({
    //       content: content, // 聊天内容
    //       contentType: contentType, // 聊天消息类型 1 文字 2 图片 3 文件 4 其他
    //       unreadCount: msgSessionData.unreadCount + 1, // 消息未读数
    //       time: time, // 发送时间
    //     })
    //     .where({ toId })
    //     .execute();
    // } else {
    //   const msgParams = {
    //     fromId: fromId, // 发送者id
    //     toId: toId, // 接受者id
    //     name: groupName, // 最后一条消息发送者名字
    //     imgUrl: groupImgUrl, // 最后一条消息发送者头像
    //     content: content, // 聊天内容
    //     contentType: contentType, // 聊天消息类型 1 文字 2 图片 3 文件 4 其他
    //     chatType: 2, // 聊天类型 1 单聊 2 群聊
    //     unreadCount: 1, // 消息未读数
    //     time: time, // 发送时间
    //   };
    //   this.msgSessionEntity.save(msgParams);
    // }
  }
  // 断开连接
  @OnWSMessage('disconnect')
  async disconnect() {}
}
